//
//  JKEmojiKeyboardViewController.swift
//  表情键盘
//
//  Created by albert on 16/6/26.
//  Copyright © 2016年 albert. All rights reserved.
//  表情键盘控制器

import UIKit

class JKEmojiKeyboardViewController: UIViewController {
    
    /** 保存所有组表情数据 */
    var packages: [JKEmojiKeyboardPackage] = JKEmojiKeyboardPackage.loadEmojiPachages()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.redColor()
        
        // 1.添加子控件
        view.addSubview(collectionView)
        view.addSubview(toolBar)
        
        // 2.布局子控件
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        toolBar.translatesAutoresizingMaskIntoConstraints = false
        
        let dict = ["collectionView" : collectionView, "toolBar" : toolBar]
        var cons = NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[collectionView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict)
        cons += NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[toolBar]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict)
        cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[collectionView]-[toolBar(49)]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict)
        view.addConstraints(cons)
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
        // 表情键盘出来的时候默认显示默认表情
        let indexPath = NSIndexPath(forItem: 0, inSection: 1)
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
    }
    
    /** 点击底部工具条按钮 */
    @objc private func itemClick(item: UIBarButtonItem) {
        let indexPath = NSIndexPath(forItem: 0, inSection: item.tag)
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
    }
    
    // MARK: - 懒加载
    /** collectionView */
    private lazy var collectionView: UICollectionView = {
        let clv = UICollectionView(frame: CGRectZero, collectionViewLayout: JKEmojiKeyboardFlowLayout())
        
        clv.backgroundColor = UIColor.greenColor()
        clv.dataSource = self
        clv.delegate = self
        clv.registerClass(JKEmojiKeyboardCell.self, forCellWithReuseIdentifier: "keyboardCell")
        
        return clv
    }()
    
    /** 底部按钮工具条 */
    private lazy var toolBar: UIToolbar = {
        let tb = UIToolbar()
        
        tb.tintColor = UIColor.lightGrayColor()
        
        var items = [UIBarButtonItem]()
        var index = 0
        for title in ["最近", "默认", "Emoji", "浪小花"] {
            
            // 1.创建item
            let item = UIBarButtonItem(title: title, style: UIBarButtonItemStyle.Plain, target: self, action: "itemClick:")
            item.tag = index++
            items.append(item)
            
            // 2.创建间隙
            let flexibleItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
            items.append(flexibleItem)
        }
        items.removeLast()
        
        // 3.将item添加到toolBar上
        tb.items = items
        
        return tb
    }()
}

// MARK: - 数据源
extension JKEmojiKeyboardViewController: UICollectionViewDataSource, UICollectionViewDelegate {
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return packages.count
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return packages[section].emoticons?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("keyboardCell", forIndexPath: indexPath) as! JKEmojiKeyboardCell
        
        let emojiIcon = packages[indexPath.section].emoticons![indexPath.item]
        
        cell.emojiIcon = emojiIcon
        
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let package = packages[indexPath.section]
        let emoticon = package.emoticons![indexPath.item]
        
        // 每使用一次就+1
        emoticon.useCount++
        
        // 判断是否是删除按钮
        if !emoticon.isDeleteButton {
            // 将当前点击的表情添加到最近组中
            packages[0].addLatestEmoji(emoticon)
        }
    }
}

// MARK: - 自定义流水布局
class JKEmojiKeyboardFlowLayout: UICollectionViewFlowLayout {
    override func prepareLayout() {
        super.prepareLayout()
        
        // 1.计算cell宽度
        let width = UIScreen.mainScreen().bounds.size.width / 7
        let height = collectionView!.frame.height / 3
        itemSize = CGSize(width: width, height: height)
        minimumInteritemSpacing = 0
        minimumLineSpacing = 0
        scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        // 2.设置collectionView
        collectionView?.bounces = false
        collectionView?.pagingEnabled = true
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.showsVerticalScrollIndicator = false
        
        // 还是直接算cell高度吧，这样还是有bug，比如collectionView的高度不足以显示三行
        // 3.设置间隙，如果不处理的话，系统会默认把间隙添加到cell之间，这里将间隙调整到上下位置，保证cell之间没有间隙
        // 注意：在iPhone4/4s上如果写为0.5会有bug
        //let offsetY = (collectionView!.frame.height - 3 * width) * 0.4999
        //collectionView?.contentInset = UIEdgeInsets(top: offsetY, left: 0, bottom: offsetY, right: 0)
    }
}
